package org.darkforest.common.services.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.darkforest.common.services.ActivitySignService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.constant.Constant;
import org.darkforest.dao.mapper.ActivityGiftMapper;
import org.darkforest.dao.mapper.ActivityMapper;
import org.darkforest.dao.mapper.ActivitySignMapper;
import org.darkforest.model.Activity;
import org.darkforest.model.ActivityGift;
import org.darkforest.model.ActivitySign;
import org.darkforest.model.Member;
import org.darkforest.vo.AjaxReturnData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ActivitySignServiceImpl implements ActivitySignService {
    Logger logger = LoggerFactory.getLogger(ActivitySignServiceImpl.class);

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityGiftMapper activityGiftMapper;

    @Autowired
    private ActivitySignMapper activitySignMapper;

    @Override
    public AjaxReturnData insertSelective(Member member, ActivitySign signsRecord) {
        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        // 根据活动类型取得活动编号
        Activity activity = new Activity();
        activity.setActivityType(Constant.ACTIVITY_TYPE_SIGN);
        activity.setCurrentTime(DateUtil.toUnixTimeStamp(DateUtil.toTimeString(new Date())));
        activity.setActivityState(true);
        List<Activity>  activityList = activityMapper.selectListByCondition(activity);
        // 活动还没有创建时
        if (activityList == null || activityList.size() == 0) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("1");
            ajaxReturnData.setMessage("签到活动还未创建");
            return ajaxReturnData;
        }
        // 签到活动只会有一个
        Activity activityDB = activityList.get(0);

        // 活动礼品ID的取得
        ActivityGift activityGift = new ActivityGift();
        activityGift.setActivityId(activityDB.getActivityId());
        List<ActivityGift> activityGiftList = activityGiftMapper.selectListByCondition(activityGift);
        // 活动礼品还没有创建时
        if (activityGiftList == null || activityGiftList.size() == 0) {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("2");
            ajaxReturnData.setMessage("签到活动礼品还未创建");
            return ajaxReturnData;
        }

        // 当前用户的最近一次签到记录的取得
        ActivitySign activitySign = new ActivitySign();
        activitySign.setActivityId(activityDB.getActivityId());
        activitySign.setMemberId(member.getMemberId());
        activitySign.setPageSwitch(false);
        ActivitySign activitySignLast = activitySignMapper.selectLastByMember(activitySign);

        // 签到时间(今天)
        Date currSignDate = new Date();
        // 测试用（根据选择的日期设定签到时间）
        //Date currSignDate = DateUtil.toIntDate(signsRecord.getSignTime());
        logger.info("#########################################signsRecord.signTime="+DateUtil.toTimeString(currSignDate));
        logger.info("#########################################signsRecord.signTimeStr="+signsRecord.getSignTimeStr());

        // 连续签到FLG
        boolean continuousDayFlg = false;
        boolean sameMonthFlg = false;
        // 连续签到天数
        Integer daysContinuous = 0;
        // 第一次签到时
        if ((activitySignLast == null) || (activitySignLast.getSignId() == null)) {
            logger.info("#########################################activitySignLast is null == "+ (activitySignLast == null));
            daysContinuous = 1;
        } else {
            // 第一次签到以外的场合
            // 需要转化为 年月日的形式  DateUtil.toDateString(new Date())
            //  activitySignLast.getSignDateStr() %Y-%m-%d
            String lastSignDate = activitySignLast.getSignDateStr();
            logger.info("lastSignDate="+lastSignDate);

            // 今天已签过到的就不能再签了
            if (lastSignDate.equals(DateUtil.toDateString(currSignDate))) {
                ajaxReturnData.setResult(false);
                ajaxReturnData.setType("3");
                ajaxReturnData.setMessage("您今天已签到，欢迎明天再来。");
                return ajaxReturnData;
            }
            // 当前用户昨天签到的话就用昨天的数值+1， 昨天没有签到的话就设为1
            // 只要是连续的签到，daysContinuous就+1
            String yesterday = DateUtil.toDateString(DateUtil.addDay(currSignDate, -1));
            if (lastSignDate.equals(yesterday)) {
                daysContinuous = activitySignLast.getDaysContinuous() + 1;
                continuousDayFlg = true;
            } else {
                daysContinuous = 1;
            }
            // 上次签到和今天是否属于用同一个月(yyyy-mm-dd)
            String signMonth = lastSignDate.substring(0, 7);
            String currMonth = DateUtil.dateToString(currSignDate, DateUtil.YEAR_MONTH_PATTERN);
            if (signMonth.equals(currMonth)) {
                sameMonthFlg = true;
            }
        }
        // 连续奖励天数
        Integer daysContinuousReward = 0;
        // 累计奖励天数
        Integer daysTotalReward = 0;
        // 礼品状态 0:未到领取时间 1:未领取 2:已领取
        String giftState = "0";
        // 礼品id
        String giftId = null;
        // 中奖的话礼品类型的设定
        Integer giftType = null;
        // 礼品说明
        String giftDescription = null;
        logger.info("##############################activityGiftList.size()="+activityGiftList.size());
        // 将activityGiftList内GiftType相同的多条数据合并为一条
        Map<Integer, List<ActivityGift>> giftMap = new HashMap<Integer, List<ActivityGift>>();
        List<ActivityGift> activityGiftListTemp = null;
        // 将LIST的数据放到MAP
        for(ActivityGift activityGiftTemp1: activityGiftList) {
            if (giftMap.containsKey(activityGiftTemp1.getGiftType())) {
                activityGiftListTemp = giftMap.get(activityGiftTemp1.getGiftType());
                activityGiftListTemp.add(activityGiftTemp1);
            } else {
                activityGiftListTemp = new ArrayList<ActivityGift>();
                activityGiftListTemp.add(activityGiftTemp1);
                giftMap.put(activityGiftTemp1.getGiftType(), activityGiftListTemp);
            }
        }
        // 将MAP的数据放到LIST
        ActivityGift activityGiftTemp = null;
        activityGiftListTemp = new ArrayList<ActivityGift>();
        for(Integer key : giftMap.keySet()){
            List<ActivityGift> value = giftMap.get(key);
            activityGiftTemp = value.get(0);
            // 取得库存大于0的， 如果都不大于0.就取第一条
            if (activityGiftTemp.getGiftStorage() <= 0 ) {
                for(ActivityGift activityGift1 : value){
                    if (activityGift1.getGiftStorage() > 0 ) {
                        activityGiftTemp = activityGift1;
                        break;
                    }
                }
            }
            activityGiftListTemp.add(activityGiftTemp);
        }
        logger.info("##############################activityGiftListTemp.size()="+activityGiftListTemp.size());
        for (int i=0; i<activityGiftListTemp.size(); i++) {
            activityGiftTemp = activityGiftListTemp.get(i);
            // GiftType: 1：按照连续签到天数设定、2：按照累积天数设定、3：两者并且
            // reserve1设定需要满足连续签到的天数
            // reserve2设定需要满足累计签到的天数
            // 按月累计时，reserve3设定1。 不按月累计时、reserve3设定0
            // GiftState，礼品状态 0:未到领取时间 1:未领取 2:已领取
            logger.info("##############################GiftType="+activityGiftTemp.getGiftType());
            // 1：按照连续签到天数累计时
            if (activityGiftTemp.getGiftType() == 1) {
                logger.info("##############################Reserve1="+activityGiftTemp.getReserve1());
                // Reserve1必须是数字
                if (!StringUtils.isNumeric(activityGiftTemp.getReserve1())) {
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setType("4");
                    ajaxReturnData.setMessage("连续签到天数的设定不正确");
                    return ajaxReturnData;
                }
                // 第一次签到时
                if (activitySignLast == null) {
                    daysContinuousReward = 1;
                } else {
                    logger.info("##############################GiftState="+activitySignLast.getGiftState());
                    // 最近一次的数据是否已兑奖,如果已领奖，则重新开始累计
                    if ("2".equals(activitySignLast.getGiftState()) && (activitySignLast.getGiftType() == activityGiftTemp.getGiftType())) {
                        daysContinuousReward = 1;
                    } else {
                        logger.info("##############################reserve3="+activityGiftTemp.getReserve3());
                        // 按月累计时，如果不是同一个月，都重新开始累计
                        if (("1".equals(activityGiftTemp.getReserve3())) && !sameMonthFlg) {
                            daysContinuousReward = 1;
                        } else {
                            // 连续签到时
                            if (continuousDayFlg) {
                                daysContinuousReward = activitySignLast.getDaysContinuousReward() + 1;
                            } else {
                                daysContinuousReward = 1;
                            }
                        }
                    }
                }

                logger.info("##############################daysContinuousReward="+daysContinuousReward);
                //  达到需要满足连续签到的天数时（整数倍）
                if (daysContinuousReward % Integer.valueOf(activityGiftTemp.getReserve1()) == 0) {
                    // 礼品状态
                    giftState = "1";
                    // 礼品类型
                    giftType = activityGiftTemp.getGiftType();
                    // 礼品id
                    //  如果giftType()==1满足中奖条件时，就设定giftType()==1的礼品
                    //  如果giftType()==2满足中奖条件时，giftType()== 1设定的礼品将会被取消，只设定giftType()==2的礼品
                    //  如果giftType()==3满足中奖条件时，giftType()== 1、2设定的礼品将会被取消，只设定giftType()==3的礼品
                    giftId = activityGiftTemp.getGiftId().toString();
                    giftDescription = "您已连续签到" + daysContinuousReward + "天，";
                    if (daysContinuousReward == Integer.valueOf(activityGiftTemp.getReserve1())) {
                        giftDescription = giftDescription + "特送礼品：";
                    } else {
                        giftDescription = giftDescription + "再送礼品：";
                    }
                    giftDescription = giftDescription + activityGiftTemp.getGiftName();
                }
            }
            // 2：按照累计天数累计时
            if (activityGiftTemp.getGiftType() == 2) {
                logger.info("##############################Reserve2="+activityGiftTemp.getReserve2());
                // Reserve2必须是数字
                if (!StringUtils.isNumeric(activityGiftTemp.getReserve2())) {
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setType("4");
                    ajaxReturnData.setMessage("累计签到天数的设定不正确");
                    return ajaxReturnData;
                }
                // 第一次签到时
                if (activitySignLast == null) {
                    daysTotalReward = 1;
                } else {
                    logger.info("##############################GiftState="+activitySignLast.getGiftState());
                    // 最近一次的数据是否已兑奖,如果已领奖，则重新开始累计
                    if ("2".equals(activitySignLast.getGiftState()) && (activitySignLast.getGiftType() == activityGiftTemp.getGiftType())) {
                        daysTotalReward = 1;
                    } else {
                        logger.info("##############################reserve3="+activityGiftTemp.getReserve3());
                        // 按月累计时，如果不是同一个月，都重新开始累计
                        if (("1".equals(activityGiftTemp.getReserve3())) && !sameMonthFlg) {
                            daysTotalReward = 1;
                        } else {
                            // 连续签到时
                            daysTotalReward = activitySignLast.getDaysTotalReward() + 1;
                        }
                    }
                }
                //  达到需要满足累计签到的天数时（整数倍）
                if (daysTotalReward % Integer.valueOf(activityGiftTemp.getReserve2()) == 0) {
                    // 礼品状态
                    giftState = "1";
                    // 礼品类型
                    giftType = activityGiftTemp.getGiftType();
                    // 礼品id
                    //  如果giftType()==1满足中奖条件时，就设定giftType()==1的礼品
                    //  如果giftType()==2满足中奖条件时，giftType()== 1设定的礼品将会被取消，只设定giftType()==2的礼品
                    //  如果giftType()==3满足中奖条件时，giftType()== 1、2设定的礼品将会被取消，只设定giftType()==3的礼品
                    giftId = activityGiftTemp.getGiftId().toString();
                    giftDescription = "您已累计签到" + daysTotalReward + "天，";
                    if (daysTotalReward == Integer.valueOf(activityGiftTemp.getReserve2())) {
                        giftDescription = giftDescription + "特送礼品：";
                    } else {
                        giftDescription = giftDescription + "再送礼品：";
                    }
                    giftDescription = giftDescription + activityGiftTemp.getGiftName();
                }
            }
            // 3：两者并且(连续签到天数 和 累积天数都需要满足时)
            if (activityGiftTemp.getGiftType() == 3) {
                logger.info("##############################Reserve1="+activityGiftTemp.getReserve1());
                logger.info("##############################Reserve2="+activityGiftTemp.getReserve2());
                // Reserve1、Reserve2必须是数字
                if (!StringUtils.isNumeric(activityGiftTemp.getReserve1()) || !StringUtils.isNumeric(activityGiftTemp.getReserve2())) {
                    ajaxReturnData.setResult(false);
                    ajaxReturnData.setType("4");
                    ajaxReturnData.setMessage("连续签到天数或累计签到天数的设定不正确");
                    return ajaxReturnData;
                }
                // 第一次签到时
                if (activitySignLast == null) {
                    daysContinuousReward = 1;
                    daysTotalReward = 1;
                } else {
                    logger.info("##############################GiftState="+activitySignLast.getGiftState());
                    // 最近一次的数据是否已兑奖,如果已领奖，则重新开始累计
                    if ("2".equals(activitySignLast.getGiftState()) && (activitySignLast.getGiftType() == activityGiftTemp.getGiftType())) {
                        daysContinuousReward = 1;
                        daysTotalReward = 1;
                    } else {
                        logger.info("##############################reserve3="+activityGiftTemp.getReserve3());
                        // 按月累计时，如果不是同一个月，都重新开始累计
                        if (("1".equals(activityGiftTemp.getReserve3())) && !sameMonthFlg) {
                            daysContinuousReward = 1;
                            daysTotalReward = 1;
                        } else {
                            // 连续签到时
                            if (continuousDayFlg) {
                                daysContinuousReward = activitySignLast.getDaysContinuousReward() + 1;
                            } else {
                                daysContinuousReward = 1;
                            }
                            daysTotalReward = activitySignLast.getDaysTotalReward() + 1;
                        }
                    }
                }
                //  达到需要满足连续签到的天数 和 累计签到的天数时（正数倍）
                if ((daysContinuousReward % Integer.valueOf(activityGiftTemp.getReserve1()) == 0) &&
                        (daysTotalReward % Integer.valueOf(activityGiftTemp.getReserve2())) == 0) {
                    // 礼品状态
                    giftState = "1";
                    // 礼品类型
                    giftType = activityGiftTemp.getGiftType();
                    // 礼品id
                    //  如果giftType()==1满足中奖条件时，就设定giftType()==1的礼品
                    //  如果giftType()==2满足中奖条件时，giftType()== 1设定的礼品将会被取消，只设定giftType()==2的礼品
                    //  如果giftType()==3满足中奖条件时，giftType()== 1、2设定的礼品将会被取消，只设定giftType()==3的礼品
                    giftId = activityGiftTemp.getGiftId().toString();
                    giftDescription = "您已连续签到" + daysContinuousReward + "天，累计签到" + daysTotalReward + "天，";
                    if ((daysContinuousReward == Integer.valueOf(activityGiftTemp.getReserve1())) &&
                            (daysTotalReward == Integer.valueOf(activityGiftTemp.getReserve2()))) {
                        giftDescription = giftDescription + "特送礼品：";
                    } else {
                        giftDescription = giftDescription + "再送礼品：";
                    }
                    giftDescription = giftDescription + activityGiftTemp.getGiftName();
                }
            }
        }

        // 签到数据的登录
        ActivitySign activitySignInsert = new ActivitySign();
        // 活动编号
        activitySignInsert.setActivityId(activityDB.getActivityId());
        // 签到人编号
        activitySignInsert.setMemberId(member.getMemberId());
        // 签到时间
        activitySignInsert.setSignTime(DateUtil.toUnixTimeStamp(DateUtil.toTimeString(currSignDate)));
        // 连续签到天数
        activitySignInsert.setDaysContinuous(daysContinuous);
        // 连续奖励天数
        activitySignInsert.setDaysContinuousReward(daysContinuousReward);
        // 累计奖励天数
        activitySignInsert.setDaysTotalReward(daysTotalReward);
        // 礼品状态 0:未到领取时间 1:未领取 2:已领取
        activitySignInsert.setGiftState(giftState);
        // 礼品id、礼品类型、礼品说明
        if (StringUtils.isNotEmpty(giftId)) {
            activitySignInsert.setGiftId(giftId);
            activitySignInsert.setGiftType(giftType);
            giftDescription = giftDescription + "，请按活动说明中有关领取地点和时间及时领取";
            activitySignInsert.setGiftDescription(giftDescription);
        }

        // 领取人编号、领取时间不设定(领取礼品时再设定)

        activitySignMapper.insertSelective(activitySignInsert);

        ajaxReturnData.setResult(true);
        ajaxReturnData.setMessage("签到成功");

        return ajaxReturnData;
    }

    @Override
    public AjaxReturnData reciveGift(Integer signId) {
        AjaxReturnData ajaxReturnData = new AjaxReturnData();

        // 中奖礼品的取得
        ActivitySign activitySign = activitySignMapper.selectByPrimaryKey(signId);
        String[] gifts = activitySign.getGiftId().split(",");
        int updateCount = 0;
        ActivityGift activityGift = null;
        for(int i=0; i<gifts.length; i++){
            activityGift = activityGiftMapper.selectByPrimaryKey(Integer.valueOf(gifts[i]));

            if (activityGift.getGiftStorage() == 0) {
                ajaxReturnData.setResult(false);
                ajaxReturnData.setType("1");
                ajaxReturnData.setUrl("activityId=" + activitySign.getActivityId() + "&&memberId="+ activitySign.getMemberId());
                ajaxReturnData.setMessage("礼品库存不足");
                return ajaxReturnData;
            }

            int giftStorage = activityGift.getGiftStorage() - 1;
            activityGift.setGiftStorage(giftStorage);
            int j = activityGiftMapper.updateByPrimaryKey(activityGift);
            updateCount = updateCount + j;
        }

        //更新签到记录礼品领取信息
        activitySign.setGiftState("2");
        // 领取者.....
        activitySign.setGiftReceiveTime(DateUtil.unixTimeStampInt().intValue());
        int k = activitySignMapper.updateByPrimaryKey(activitySign);

        if ((k > 0) && (updateCount == gifts.length) ) {
            ajaxReturnData.setResult(true);
            ajaxReturnData.setMessage("领取成功");
        } else {
            ajaxReturnData.setResult(false);
            ajaxReturnData.setType("2");
            ajaxReturnData.setMessage("领取失败");
        }

        ajaxReturnData.setUrl("activityId=" + activitySign.getActivityId() + "&&memberId="+ activitySign.getMemberId());
        return ajaxReturnData;
    }
}
